<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>
          <i class="el-icon-lx-cascades"></i> 基础表格
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="container">
      <div class="handle-box">
        <el-button
          type="primary"
          icon="el-icon-delete"
          class="handle-del mr10"
          @click="delAllSelection"
          >批量删除</el-button
        >
        <el-button type="primary" icon="el-icon-plus" @click="add"
          >添加</el-button
        >
      </div>
      <el-table
        :data="swiperlist"
        border
        class="table"
        ref="multipleTable"
        header-cell-class-name="table-header"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="id"
          label="ID"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column label="头像(查看大图)" align="center">
          <template slot-scope="scope">
            <el-image
              class="table-td-thumb"
              :src="scope.row.url"
              :preview-src-list="[scope.row.url]"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="url" label="地址"></el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <el-tag type="success">{{ swiperlei[scope.row.type - 1] }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-edit"
              @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              type="text"
              icon="el-icon-delete"
              class="red"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :current-page="query.page"
          :page-size="query.pagelimit"
          :total="pageTotal"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 添加框 -->
    <el-dialog title="添加" :visible.sync="adds" width="30%">
      <div class="T-main">
        <div class="m-3">
          <div class="m-c">
            <el-form
              :model="ruleForm"
              ref="ruleForm"
              label-width="100px"
              class="demo-ruleForm"
            >
              <!-- 头像 -->
              <el-form-item label="头像" required>
                <el-upload
                  class="avatar-uploader"
                  action="https://goods.zzgoodqc.cn/index.php/index/upload/uploadimg"
                  :show-file-list="false"
                  :before-upload="beforeAvatarUpload"
                  :on-progress="handleAvatarProgress"
                  :data="imgs"
                >
                  <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
              <!-- 状态 -->
              <el-form-item
                label="状态"
                prop="type"
                :rules="[
                  {
                    required: true,
                    message: '请选择状态',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-select v-model="ruleForm.type" placeholder="请选择">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button @click="adds = false">取 消</el-button>
                <el-button type="primary" @click="saveAdd('ruleForm')"
                  >确 定</el-button
                >
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer"> </span>
    </el-dialog>
    <!-- 编辑弹出框 -->
    <el-dialog title="编辑" :visible.sync="editVisible" width="30%">
      <div class="T-main">
        <div class="m-3">
          <div class="m-c">
            <el-form ref="form" :model="form" label-width="100px">
              <!-- 头像 -->
              <el-form-item label="头像" required>
                <el-upload
                  class="avatar-uploader"
                  action="https://goods.zzgoodqc.cn/index.php/index/upload/uploadimg"
                  :show-file-list="false"
                  :before-upload="beforeAvatarUpload"
                  :on-progress="handleAvatarProgress1"
                  :data="imgs"
                >
                  <img v-if="form.url" :src="form.url" class="avatar" />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
              <!-- 状态 -->
              <el-form-item
                label="状态"
                prop="type"
                :rules="[
                  {
                    required: true,
                    message: '请选择状态',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-select
                  v-model="swiperlei[form.type - 1]"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEdit('form')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getSwiper, delpic, getImgUrl, addImgs } from '../../api/http'

export default {
  name: 'ZhenghaobanSwiper',

  data() {
    return {
      swiperlei: ['首页', '咨询', '生活', '其他'],
      swiperlist: [],
      options: [
        {
          value: '1',
          label: '首页',
        },
        {
          value: '2',
          label: '咨询',
        },
        {
          value: '3',
          label: '生活',
        },
        {
          value: '4',
          label: '其他',
        },
      ],
      ruleForm: {
        type: '',
        url: '',
      },
      form: [],
      editVisible: false,
      adds: false,
      query: {
        type: '',
        page: 1,
        pagelimit: 10,
      },
      idx: -1,
      id: -1,
      imgs: {},
      multipleSelection: [],
      pageTotal: 0,
      imageUrl: '',
      imgBs64: '',
      imgBs641: '',
      newImgUrl: '',
    }
  },
  created() {
    this.getSwiperlist()
  },

  methods: {
    getSwiperlist() {
      getSwiper(this.query).then((res) => {
        console.log(res)
        this.swiperlist = res.data.data
        this.pageTotal = res.data.pagecount
      })
    },
    //获得base64格式的图片
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        let reader = new FileReader()
        let imgResult = ''
        reader.readAsDataURL(file)
        reader.onload = function () {
          imgResult = reader.result
        }
        reader.onerror = function (error) {
          reject(error)
        }
        reader.onloadend = function () {
          resolve(imgResult)
        }
      })
    },
    handleAvatarProgress(event, file, fileList) {
      console.log(file)
      console.log(fileList)
      this.imageUrl = URL.createObjectURL(file.raw)
      this.getBase64(file.raw).then((res) => {
        this.imgBs64 = res
      })
    },
    handleAvatarProgress1(event, file, fileList) {
      console.log(fileList)
      this.form.url = URL.createObjectURL(file.raw)
      this.getBase64(file.raw).then((res) => {
        this.imgBs641 = res
      })
    },

    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 编辑操作
    handleEdit(index, row) {
      this.idx = index
      this.form = row

      this.editVisible = true
    },
    // 保存编辑
    saveEdit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let base = {
            imgurl: this.imgBs641,
          }
          getImgUrl(base).then((res) => {
            if (res.code !== 0) return this.$message.error('请重新上传图片')
            let obj = {
              id: this.form.id,
              type: this.form.type,
              url: 'https://goods.zzgoodqc.cn' + res.data.url,
            }

            addImgs(obj).then((res) => {
              if (res.code !== 0) return this.$message.error(res.msg)
              this.editVisible = false

              this.$message.success(`修改第 ${this.idx + 1} 行成功`)

              this.getSwiperlist()
            })
          })
        } else {
          return false
        }
      })
    },
    // 删除操作
    handleDelete(index, row) {
      this.$confirm('确定要删除吗？', '提示', {
        type: 'warning',
      })
        .then(() => {
          let id = {
            id: row.id,
          }
          delpic(id).then((res) => {
            if (res.code !== 0) return this.$message.error(res.msg)
            this.$message.success('删除成功')
            this.getSwiperlist()
          })
        })
        .catch(() => {})
    },
    // 多选操作
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    //批量删除
    delAllSelection() {
      // var ids = this.multipleSelection.map((item) => item.id)
      // this.$confirm('确定要删除吗？', '提示', {
      //   type: 'warning',
      // })
      //   .then(() => {
      //     delTableList(ids.join(','), sessionStorage.getItem('token')).then(
      //       (res) => {
      //         if (res.code !== 0)
      //           return this.$message.error('请选择你要删除的数据！')
      //         this.$message.success('删除成功')
      //               this.getSwiperlist()
      //         this.multipleSelection = []
      //       }
      //     )
      //   })
      //   .catch(() => {})
    },

    //打开添加窗口
    add() {
      this.adds = true
    },
    saveAdd(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let base = {
            imgurl: this.imgBs64,
          }
          getImgUrl(base).then((res) => {
            if (res.code !== 0) return this.$message.error(res.msg)
            let obj = {
              type: this.ruleForm.type - 0,
              url: 'https://goods.zzgoodqc.cn' + res.data.url,
            }
            addImgs(obj).then((res) => {
              if (res.code !== 0) return this.$message.error(res.msg)
              this.adds = false
              this.$message.success('添加成功')
              this.getSwiperlist()
            })
          })
        } else {
          return false
        }
      })
    },
    // 分页导航
    handlePageChange(val) {
      this.$set(this.query, 'page', val)
      this.getSwiperlist()
    },
  },
}
</script>

<style scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}
.table {
  width: 100%;
  font-size: 14px;
}
.red {
  color: #ff0000;
}
.mr10 {
  margin-right: 10px;
}
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  width: 100px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.T-main {
  padding: 20px;
}
.T-main .m-3 {
  background: #fff;
  width: 100%;
}
.T-main .m-3 .m-c {
  width: 400px;
  margin: 0 auto;
}
.T-main .m-3 .m-c .m-o {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin: 20px 0;
}
.T-main .m-3 .m-c .m-o p {
  width: 35px;
}
::v-deep .el-upload--text {
  width: 220px;
}
</style>
